package com.sailfish.springbootdemo.controller.db1;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.sailfish.springbootdemo.dao.db1.BaseCapacityRuleDao;
import com.sailfish.springbootdemo.dao.db1.TechDeviceParamDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.BaseCapacityRule;
import com.sailfish.springbootdemo.pojo.db1.TechDeviceParam;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.HttpUtil;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/common")
@CrossOrigin
public class CommonController {

//    @Value("${personal.config.file.host-prefix-url}")
//    private String hostPrefixUrl ;

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;

    @Value("${personal.config.env}")
    private String env;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private AmazonS3 amazonS3;

    @Value("${personal.config.amazon-s3.url}")
    private String url;
    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;


    /**
     * 上传图片
     *
     * @param req
     * @return
     */
    @PostMapping("/uploadPicture")
    public Map<String, String> uploadPicture(HttpServletRequest req) {
        try {
            Map<String, String> map = new HashMap<>();
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile file = mRequest.getFile("file");

            //获取项目目录
            /*String projectPath = System.getProperty("user.dir");
            System.out.println("项目路径：" + projectPath);*/

            String format = sdf.format(new Date());
            File folder = new File(fileSaveUrl + "uploadPicture\\" + format);

            String filePath = "";
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            String newName = oldName.substring(0, oldName.lastIndexOf(".")) + UUID.randomUUID().toString() +
                    oldName.substring(oldName.lastIndexOf("."), oldName.length());

            file.transferTo(new File(folder, newName));
            filePath = "uploadPicture\\" + format + "\\" + newName;

            //System.out.println(filePath);
            map.put("name", newName);
            map.put("oldName", oldName);
            //map.put("url", hostPrefixUrl + filePath);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传文件
     *
     * @param req
     * @return
     */
    @PostMapping("/uploadFile")
    public Map<String, String> uploadFile(HttpServletRequest req) {

        try {
            Map<String, String> map = new HashMap<>();
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile file = mRequest.getFile("file");

            //获取项目目录
            //获取项目目录
            /*String projectPath = System.getProperty("user.dir");
            System.out.println("项目路径：" + projectPath);*/

            String format = sdf.format(new Date());
            File folder = new File(fileSaveUrl + "uploadFile\\" + format);

            String filePath = "";
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            String newName = oldName.substring(0, oldName.lastIndexOf(".")) + UUID.randomUUID().toString() +
                    oldName.substring(oldName.lastIndexOf("."), oldName.length());

            file.transferTo(new File(folder, newName));
            filePath = "uploadFile\\" + format + "\\" + newName;

            System.out.println(filePath);
            //return filePath;
            map.put("name", newName);
            map.put("oldName", oldName);
            //map.put("url", hostPrefixUrl + filePath);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传文件(统一)
     *
     * @param req
     * @return
     */
    @PostMapping("/commonUploadFiles")
    public Result commonUploadFiles(HttpServletRequest req) {

        try {
            Map<String, String> map = new HashMap<>();
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            MultipartFile file = mRequest.getFile("file");

            //获取项目目录
            //获取项目目录
            /*String projectPath = System.getProperty("user.dir");
            System.out.println("项目路径：" + projectPath);*/

            int picLength = 0;
            int picWidth = 0;
            try {
                BufferedImage image = ImageIO.read(file.getInputStream());
                picLength = image.getWidth();
                picWidth = image.getHeight();
            } catch (Exception e) {
                e.printStackTrace();
            }

            String format = sdf.format(new Date());
            File folder = new File(fileSaveUrl + "commonUploadFiles\\" + format);

            String filePath = "";
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            String newName = oldName.substring(0, oldName.lastIndexOf(".")) + UUID.randomUUID().toString() +
                    oldName.substring(oldName.lastIndexOf("."), oldName.length());

            file.transferTo(new File(folder, newName));
            filePath = "commonUploadFiles\\" + format + "\\" + newName;

            System.out.println(filePath);
            //return filePath;
            map.put("name", newName);
            map.put("oldName", oldName);
            map.put("url", filePath);
            map.put("picLength", picLength + "");
            map.put("picWidth", picWidth + "");
            //map.put("hostPrefixUrl",  hostPrefixUrl);
            return ResultUtil.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 上传文件(统一)
     *
     * @param req
     * @return
     */
    @PostMapping("/commonUploadFilesAmazonS3")
    public Result commonUploadFilesAmazonS3(HttpServletRequest req) {

        try {
            if (env != null && env.contains("pro")) {
                Map<String, String> map = new HashMap<>();
                MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
                MultipartFile multipartFile = mRequest.getFile("file");

                int picLength = 0;
                int picWidth = 0;
                try {
                    BufferedImage image = ImageIO.read(multipartFile.getInputStream());
                    picLength = image.getWidth();
                    picWidth = image.getHeight();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String oldName = multipartFile.getOriginalFilename();
                String newName = oldName + "-" + UUID.randomUUID().toString() +
                        oldName.substring(oldName.lastIndexOf("."), oldName.length());
                String directory = "pcbaFiles";
                try {
                    //将MultipartFile转成File
                    File file = File.createTempFile("temp", ".temp");
                    InputStream inputStream = multipartFile.getInputStream();
                    OutputStream os = new FileOutputStream(file);
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                    os.close();
                    inputStream.close();
                    System.out.println("将MultipartFile转成File成功");

                    ObjectMetadata metadata = new ObjectMetadata();
                    metadata.setContentType("application/octet-stream");
                    PutObjectResult result = amazonS3.putObject(new PutObjectRequest(fileBucket,
                            directory + "/" + newName, new FileInputStream(file), metadata)
                            //配置访问权限
                            .withCannedAcl(CannedAccessControlList.PublicRead));
                    String address = directory + "/" + newName;

                    String httpUrl = url + fileBucket + "/" + address;

                    map.put("name", newName);
                    map.put("oldName", oldName);
                    map.put("url", address);
                    map.put("httpUrl", httpUrl);
                    map.put("base64", CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(url + "/" + fileBucket + "/" + address));
                    map.put("picLength", picLength + "");
                    map.put("picWidth", picWidth + "");
                    return ResultUtil.success(map);
                } catch (Exception e) {
                    System.out.println(String.format("上传文件【%s】到AmazonS3失败:", oldName) + e.getMessage());
                    return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
                }
            }else {
                // 本地方式上传
                Map<String, String> map = new HashMap<>();
                MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
                MultipartFile multipartFile = mRequest.getFile("file");

                int picLength = 0;
                int picWidth = 0;
                try {
                    BufferedImage image = ImageIO.read(multipartFile.getInputStream());
                    picLength = image.getWidth();
                    picWidth = image.getHeight();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String oldName = multipartFile.getOriginalFilename();
                String newName = oldName + "-" + UUID.randomUUID().toString() +
                        oldName.substring(oldName.lastIndexOf("."), oldName.length());

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(new Date());
                java.io.File folder = new java.io.File(fileSaveUrl + "commonUploadFiles\\" + format);

                String filePath = "";
                if (!folder.isDirectory()) {
                    folder.mkdirs();
                }
                multipartFile.transferTo(new java.io.File(folder, newName));
                filePath = "capacityFiles\\commonUploadFiles\\" + format + "\\" + newName;

                try {
                    String fileUrl = CommonUtils.getApiPrefixUrl(req) + "/" + filePath;
                    map.put("name", newName);
                    map.put("oldName", oldName);
                    map.put("url", filePath);
                    map.put("httpUrl", fileUrl);
                    map.put("picLength", picLength + "");
                    map.put("picWidth", picWidth + "");
                    map.put("base64", CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(fileUrl));
                    return ResultUtil.success(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(String.format("上传文件【%s】失败:", oldName) + e.getMessage());
                    return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 上传图片【富文本用到】
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadPictureBlob")
    public Result uploadPictureBlob(MultipartFile file) {
        try {
            if (file == null) {
                return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
            }
            Map<String, String> map = new HashMap<>();
            String format = sdf.format(new Date());
            File folder = new File(fileSaveUrl + "uploadPicture\\" + format);
            String filePath = "";
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String oldName = file.getOriginalFilename();
            String newName = oldName.substring(0, oldName.lastIndexOf(".")) + UUID.randomUUID().toString() +
                    oldName.substring(oldName.lastIndexOf("."), oldName.length());

            file.transferTo(new File(folder, newName));
            filePath = "uploadPicture\\" + format + "\\" + newName;

            //map.put("hostPrefixUrl", hostPrefixUrl);
            map.put("filePath", filePath);
            ;
            map.put("originType", "2");
            ;
            return ResultUtil.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 下载文件base64
     *
     * @param fileName
     * @return
     */
    @PostMapping("/downloadFileBase64")
    public Result downloadFileBase64(String fileName) {
        try {
            if (fileName == null || "".equals(fileName)) {
                return ResultUtil.error(500, "缺少参数fileName", "Miss Param fileName", null);
            }
            File file = new File(fileSaveUrl + "templates\\" + fileName);   //URL url = new URL(src);
            byte[] data = null;
            InputStream in = new FileInputStream(file);  //InputStream in = url.openStream();
            data = new byte[in.available()];
            in.read(data);
            in.close();
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(data);

            Map<String, Object> map = new HashMap<>();
            map.put("base64", base64);
            map.put("fileName", fileName);
            return ResultUtil.success(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    /**
     * 生成Excel
     *
     * @return
     */
    @PostMapping("/createExcel")
    public Result createExcel() {
        try {
            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet("pcb新技术管理");
            // 创建行和单元格对象
            Row row = sheet.createRow(0);
            CellStyle contextCellStyle = workbook.createCellStyle();
            contextCellStyle.setBorderBottom(BorderStyle.THIN);
            contextCellStyle.setBorderLeft(BorderStyle.THIN);
            contextCellStyle.setBorderRight(BorderStyle.THIN);
            contextCellStyle.setBorderTop(BorderStyle.THIN);
            contextCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            List<String> titleList = new ArrayList<>();
            titleList.add("项目大类");
            titleList.add("线体名称");
            titleList.add("项目小类");
            titleList.add("整线能力评估项");
            for (int a = 0; a < 4; a++) {
                sheet.setColumnWidth(a, 900 * 10);
                Cell cell = row.createCell(a);
                // 向单元格中写入数据
                cell.setCellValue(titleList.get(a));
                cell.setCellStyle(contextCellStyle);
            }
            // 导出Excel文件
            FileOutputStream outputStream = new FileOutputStream("output.xlsx");
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
